﻿// Allows the element to show a context menu when right clicked
define([
    'Wjs/Wjs',
    'Wjs/widgets/menu/Menu'
],
function () {
    'use strict';

    var type = 'ContextMenu', // Use the type registration to avoid recreating the type
    typeManager = Wjs.typeManager,
    ContextMenu = typeManager.getType(type);

    if (ContextMenu) { // It has been already loaded
        return ContextMenu;
    }

    // Renders the html from a component
    ContextMenu = Wjs.typeBuilder.define({

        type: type, // Set the type

        // Call it after calling Widget construct
        initialize: function (conf, element) {

            conf = conf || {};

            if (!conf.menu) {
                return;
            }

            if (!element.dom) {
                throw 'Element must be rendered';
            }

            var me = this,
            menu = typeManager.create('menu', conf.menu);
            menu.render();

            element.on('contextmenu', function (evt) {
                evt.preventDefault();

                menu.move(evt.pageX, evt.pageY);
                menu.show(evt);
            });

        }
    });

    typeManager.registerType(ContextMenu);

    return ContextMenu;
});